﻿<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;

use App\Services\GameMoneyReissue;
use App\Services\MemberService;
use App\Tools\SmsService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $indexBanner = DB::table('sys_config')->where('key', 'index_banner')->value('value');
        //查询今日游戏 -未发布
        $tdyDataUnpublished = DB::table('game_data')
            ->where(function ($query) use ($request) {
                if ($request->game_key) {
                    $query->where('server_name', 'like', "%{$request->game_key}%")
                        ->orWhere('server_ip', 'like', "%{$request->game_key}%");
                }
            })

            ->where(function ($query) {
                $query->where('is_every_day', 1)->where('is_mobile', '=',2);
            })
            ->orWhere(function ($query) {
                $query->whereDate('open_time', date('Y-m-d'))
                    ->whereTime('open_time', '>=', date('Y-m-d H:i:s'));
            })
            ->where('is_mobile', '=',2)
            ->orderBy('is_top', 'desc')
            ->orderBy('open_time', 'desc')
            ->inRandomOrder()
            ->get();
        $tjGames = DB::table('game_data')
            ->where(function ($query) {
                $query->where('is_every_day', 1);
                $query->where('is_top', 0);
                $query->orWhere(function ($query) {
                    $query->whereDate('open_time', date('Y-m-d'))
                        ->whereTime('open_time', '>=', date('Y-m-d H:i:s'));
                });
            })
            ->where('is_mobile', '=',2)
            ->orderBy('is_rm', 'desc')
            ->orderBy('id', 'desc')
            ->limit(5)
            ->get();
        $mobileGames = DB::table('game_data')
            ->where(function ($query) {
                $query->where('is_every_day', 1);
                $query->orWhere(function ($query) {
                    $query->whereDate('open_time', date('Y-m-d'))
                        ->whereTime('open_time', '>=', date('Y-m-d H:i:s'));
                });
            })
            ->where('is_mobile', '=',1)
            ->orderBy('id', 'desc')
            ->limit(5)
            ->get();
        // 标签筛选
        if ($request->tag_id > 0) {
            $tagGames =  DB::table('game_tag_join')
                ->where('tag_id', $request->tag_id)
                ->pluck('game_id')->toArray();
            if (!count($tagGames)) {
                $tdyDataUnpublished = [];
            } else {
                foreach ($tdyDataUnpublished as $i => $v) {
                    if (!in_array($v->id, $tagGames)) {
                        unset($tdyDataUnpublished[$i]);
                    }
                }
            }
        }
        $allGameIds = [];
        // 首沙
        $topGames = DB::table('game_data')
            ->whereDate('create_time', '=',date('Y-m-d', strtotime('-1 day')))
            ->orderBy('is_rm', 'desc')
            ->orderBy('id', 'desc')
            ->limit(1)
            ->get();
        // 次沙
        $subGames = DB::table('game_data')
            ->whereDate('create_time', '=',date('Y-m-d', strtotime('-2 day')))
            ->orderBy('is_rm', 'desc')
            ->orderBy('id', 'desc')
            ->limit(1)
            ->get();

        $nowHour = (int)date('H');
        $vl = [
            '烈火骑士','星空传奇','百战沙场','屠龙战神'
        ];
        // 排除首次沙
        foreach ($tdyDataUnpublished as $k => $item) {
            $tdyDataUnpublished[$k]->ss_prefix = '';
            foreach ($topGames as $t) {
                if ($item->id == $t->id) {
                    $tdyDataUnpublished[$k]->ss_prefix = '【首沙】';
                    break;
                }
            }
            foreach ($subGames as $s) {
                if ($item->id == $s->id) {
                    $tdyDataUnpublished[$k]->ss_prefix = '【次沙】';
                    break;
                }
            }
        }
        foreach ($tdyDataUnpublished as &$item) {
            if ($nowHour < 8) {
                $item->count = 0;
            }
            $keys = $item->id % 4;
            $item->server_ip = $vl[$keys];
            $allGameIds[] = $item->id;
        }
        foreach ($tjGames as &$item) {
            $allGameIds[] = $item->id;
        }
        foreach ($topGames as &$item) {
            $allGameIds[] = $item->id;
        }
        foreach ($subGames as &$item) {
            $allGameIds[] = $item->id;
        }
        foreach ($mobileGames as &$item) {
            $allGameIds[] = $item->id;
        }
        // 查询所有标签
        $allTags = DB::table('game_tag_join')
            ->whereIn('game_id', $allGameIds)
            ->get();
        $gameTags = [];
        $allTagIds = [];
        foreach ($allTags as $tag) {
            $gameTags[$tag->game_id][] = $tag->tag_id;
            $allTagIds[] = $tag->tag_id;
        }
        $tagMap = DB::table('game_tag')
            ->whereIn('id', $allTagIds)
            ->pluck('tag_name', 'id');
        foreach ($tdyDataUnpublished as &$item) {
            $item->url = $this->getGameUrl($item->url_json, $item->url);
            $item->tagNames = '';
            if (!empty($gameTags[$item->id])) {
                foreach ($gameTags[$item->id] as $t) {
                    $item->tagNames .= ($tagMap[$t] ?? '').', ';
                }
                $item->tagNames = trim($item->tagNames, ', ');
            }
        }
        foreach ($topGames as &$item) {
            $item->url = $this->getGameUrl($item->url_json, $item->url);
            $item->tagNames = '';
            if (!empty($gameTags[$item->id])) {
                foreach ($gameTags[$item->id] as $t) {
                    $item->tagNames .= ($tagMap[$t] ?? '').', ';
                }
                $item->tagNames = trim($item->tagNames, ', ');
            }
        }
        foreach ($subGames as &$item) {
            $item->url = $this->getGameUrl($item->url_json, $item->url);
            $item->tagNames = '';
            if (!empty($gameTags[$item->id])) {
                foreach ($gameTags[$item->id] as $t) {
                    $item->tagNames .= ($tagMap[$t] ?? '').', ';
                }
                $item->tagNames = trim($item->tagNames, ', ');
            }
        }
        foreach ($tjGames as &$item) {
            $item->url = $this->getGameUrl($item->url_json, $item->url);
            $item->tagNames = '';
            if (!empty($gameTags[$item->id])) {
                foreach ($gameTags[$item->id] as $t) {
                    $item->tagNames .= ($tagMap[$t] ?? '').', ';
                }
                $item->tagNames = trim($item->tagNames, ', ');
            }
        }
        foreach ($mobileGames as &$item) {
            $item->url = $this->getGameUrl($item->url_json, $item->url);
            $item->tagNames = '';
            if (!empty($gameTags[$item->id])) {
                foreach ($gameTags[$item->id] as $t) {
                    $item->tagNames .= ($tagMap[$t] ?? '').', ';
                }
                $item->tagNames = trim($item->tagNames, ', ');
            }
        }
        $userInfo = [];
        if (Cookie::get('token')) {
            $userInfo = DB::table("users")->where('token', Cookie::get('token'))->first();
        }
        // 邀请者
        if ($request->from_id) {
            Cookie::queue('from_id', $request->from_id);
        }
        // 邀请者
        if ($request->uid) {
            Cookie::queue('from_union_id', $request->uid);
        }
        $tags = DB::table('game_tag')
            ->orderBy('id', 'desc')
            ->get();
        return view('user.new_home', [
            'url' => $this->get_host($_SERVER['SERVER_NAME']),  // 获取顶级域名
            'today' => [                                        // 今天
                'unpublished' => $tdyDataUnpublished,           // 今天 -未发布
                'top_games' => $topGames,
                'sub_games' => $subGames,
                'tj_games' => $tjGames,
                'mobile_games' => $mobileGames,
            ],
            'is_login' => $userInfo ? true : false,
            'user_info'=> $userInfo,
            'tags'=>$tags,
            'indexBanner'=>$indexBanner,
        ]);
    }

    /**
     * get host
     *
     * @return url
     */
    function get_host($to_virify_url = ''){

        $url   = $to_virify_url ? $to_virify_url : $_SERVER['HTTP_HOST'];
        $data = explode('.', $url);
        $co_ta = count($data);

        //判断是否是双后缀
        $zi_tow = true;
        $host_cn = 'com.cn,net.cn,org.cn,gov.cn';
        $host_cn = explode(',', $host_cn);
        foreach($host_cn as $host){
            if(strpos($url,$host)){
                $zi_tow = false;
            }
        }

        //如果是返回FALSE ，如果不是返回true
        if($zi_tow == true){

            // 是否为当前域名
            if($url == 'localhost'){
                $host = $data[$co_ta-1];
            }
            else{
                $host = $data[$co_ta-2].'.'.$data[$co_ta-1];
            }

        }
        else{
            $host = $data[$co_ta-3].'.'.$data[$co_ta-2].'.'.$data[$co_ta-1];
        }

        return $host;
    }

    private function getGameUrl($extendStr, $default)
    {
        $host = $_SERVER['HTTP_HOST'];
        $rows = explode("\n", $extendStr);
        $hostMap = [];
        foreach ($rows as $row) {
            $info = explode(',', $row);
            if (count($info) != 2) {
                continue;
            }
            $hostMap[$info[0]] = $info[1];
        }
        return $hostMap[$host] ?? $default;
    }


    /**
     * 领取记录
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getLog($id)
    {
        $user_id = request()->cookie('user_id');
        $logs = DB::table('user_get_log')->select('user_get_log.*')
            ->where('game_id', $id)
            ->orderBy('recharge_time', 'desc')
            ->get();
        return view('user.user_log', [
            'logs'=>$logs,
            'user_id' => $user_id
        ]);
    }

    /**
     *防劫持教程
     */
    public function getHijackInfo(){
        return view('user.jc');
    }

    /**
     * 游戏服务器列表
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGameServer($id)
    {
        $days = request()->get('day', 't');
        $logs = DB::table('game_server')
            ->where('game_id', $id);
        if ($days == 't') {
            $logs = $logs->where('open_server_time', '<=', date('H:i:s'));
        }
        $logs = $logs->orderBy('open_server_time', 'asc')->get();
        $game = DB::table('game_data')
            ->where('id', $id)
            ->first();
        $gameOpenDay = date('Y-m-d', strtotime($game->open_time));
        $is_checked = false;
        if ($days != 't') {
            // 昨日数据
            $gameOpenDay = date('Y-m-d', strtotime('-1 day'));
        }
        foreach ($logs as $k => $log) {
            $log->is_disable = time() > strtotime($gameOpenDay . ' ' .$log->open_server_time);
            $log->is_checked = false;
            // 选中最后一个
            if (!$log->is_disable && isset($logs[$k - 1]) && !$is_checked) {
                $logs[$k - 1]->is_checked = true;
                $is_checked = true;
            }
            if ($k == $logs->count() - 1 && !$is_checked) {
                if ($log->is_disable) {
                    $log->is_checked = true;
                }else {
                    $logs[$k - 1]->is_checked = true;
                }
                $is_checked = true;
            }
        }
        return response()->json(['message' => '', 'success' => 'true', 'data' => $logs]);
    }

    /**
     * 提交领取信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function commitForm(Request $request)
    {
        $nowHour = (int)date('H');
        if ($nowHour < 8) {
            return response()->json(['message' => '礼包已被抢完', 'success' => 'false']);
        }
        //验证表单
        $this->validate($request, [
            'game_num' => ['required','string','max:50'],
            'game_num_re' => ['required','string','max:50'],
            'game_id' => ['required','int'],
            'captcha' => ['required','string','max:6'],
            'server_id' => ['required','int'],
        ]);
        if ($request->game_num != $request->game_num_re) {
            return response()->json(['message' => '两次输入的游戏账号不一致', 'success' => 'false']);
        }
        if (!captcha_check($request->captcha)) {
            return response()->json(['message' => '验证码错误', 'success' => 'false']);
        }
        // 查询游戏信息
        $game = DB::table('game_data')
            ->where('id', $request->game_id)
            ->first();
        if (!$game) {
            return response()->json(['message' => '游戏信息错误', 'success' => 'false']);
        }

        // 是否通区
        if ($game->is_tq == 1) {
            $isGet = DB::table('draw_log')
                ->where('game_url', $game->server_name)
                ->where('game_num', $request->game_num)
                ->where('draw_id', '>', 0)
                ->count();
            if ($isGet) {
                return response()->json(['message' => '改账号已经领取奖励，请勿重复领取', 'success' => 'false']);
            }
        }
        $server = DB::table('game_server')
            ->where('id', $request->server_id)
            ->first();
        if (!$server) {
            return response()->json(['message' => '服务器信息错误', 'success' => 'false']);
        }
        if ($server->game_id != $game->id) {
            return response()->json(['message' => '服务器信息错误', 'success' => 'false']);
        }
        if ($game->count <= $game->get_num) {
            return response()->json(['message' => '已经被抢光了', 'success' => 'false']);
        }
        // 判断当前用户是否已经抢购过
        $uid = $request->userInfo->id;
        $isGet = DB::table('draw_log')
            ->where('game_url', $game->server_name)
            ->where('game_server', $server->server_name)
            ->where('user_id', $uid)
            ->where('draw_id', '>', 0)
            ->whereDay('create_time', '=', date('Y-m-d'))
            ->count();
        if ($isGet) {
            return response()->json(['message' => '请勿重复领取', 'success' => 'false']);
        }
        DB::beginTransaction();
        try {
            //更新游戏信息
            $res = DB::table('game_data')
                ->where('id', $request->game_id)
                ->whereColumn('count', '>', 'get_num')
                ->increment('get_num');
            if (!$res) {
                throw new \Exception('游戏信息更新失败');
            }
            // 插入获取数据
            /*$res = DB::table('user_get_log')->insert([
                'game_id' => $game->id,
                'server_id' => $server->id,
                'user_id' => $uid,
                'game_num' => $request->game_num,
                'create_time' => time(),
                'game_name' => $game->server_name,
                'server_name' => $server->server_name,
                'money' => $game->money
            ]);*/
            $res = DB::table('draw_log')->insertGetId([
                'user_id' => $uid,
                // 'draw_id' => 0,
                'is_luck' => 1,
                'money' => 3,
                'create_time' => date('Y-m-d H:i:s'),
                'game_num' => $request->game_num,
                'game_url' => $game->server_name,
                'game_server' => $server->server_name,
                'status' => 2,
                'date' => '今日',
                'draw_id' => 13
            ]);
            if (!$res) {
                throw new \Exception('领取信息写入失败');
            }
            DB::commit();
            return response()->json(['message' => '编辑成功。', 'success' => 'true']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'success' => 'false']);
        }
    }

    /**
     * 提交获奖信息页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getCommitDrawPage($id)
    {
        $log = DB::table('draw_log')->find($id);
        $tdyDataUnpublished = DB::table('game_data')
            ->where(function ($query) {
                $query->where('is_every_day', 1);
            })
            ->orWhere(function ($query) {
                $query->whereDate('open_time', date('Y-m-d'))
                    ->whereTime('open_time', '>=', date('Y-m-d H:i:s'));
            });
        if ($log->draw_id == 1 || $log->draw_id == 2) {
            $tdyDataUnpublished = $tdyDataUnpublished
                ->orderBy('id', 'desc')
                ->limit(7)
                ->get();
        } else {
            $tdyDataUnpublished = $tdyDataUnpublished
                ->orderBy('open_time', 'desc')
                ->inRandomOrder()
                ->get();
        }

        return view('user.commit_draw_info', [
            'id'=>$id,
            'log'=>$log,
            'games' => $tdyDataUnpublished
        ]);
    }

    /**
     * 重新提交领取新页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showReCommitGetLog($id)
    {
        $log = DB::table('draw_log')->find($id);
        return view('user.re_commit_get_info', [
            'id'=>$id,
            'log'=>$log,
        ]);

    }

    /**
     * 重新提交领取信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function reCommitGetLog(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'id' => ['required', 'int'],
            'game_num' => ['required','string','max:50'],
            'game_num_re' => ['required','string','max:50'],
            'captcha' => ['required','string','max:6'],
        ]);
        if ($request->game_num != $request->game_num_re) {
            return response()->json(['message' => '两次输入的游戏账号不一致', 'success' => 'false']);
        }
        if (!captcha_check($request->captcha)) {
            return response()->json(['message' => '验证码错误', 'success' => 'false']);
        }
//        您的中奖信息正在处理中，请耐心等待
        // 查询游戏信息
        $log = DB::table('user_get_log')
            ->where('id', $request->id)
            ->first();
        if (!$log) {
            return response()->json(['message' => '记录不存在', 'success' => 'false']);
        }
        if ($log->status != 3) {
            return response()->json(['message' => '记录无需重新提交', 'success' => 'false']);
        }
        if ($log->user_id != $request->cookie('user_id')) {
            return response()->json(['message' => '用户非法', 'success' => 'false']);
        }
        // 写入新纪录
        DB::table('user_get_log')
            ->where('id', $request->id)
            ->update([
                'game_num' => $request->game_num,
                'status' => 1,
                'msg' => ''
            ]);
        return response()->json(['message' => '提交成功。', 'success' => 'true']);
    }

    /**
     * 是否需要绑定手机号
     * @return \Illuminate\Http\JsonResponse
     */
    public function needBindMobile()
    {
        if (\request()->userInfo->mobile) {
            return response()->json(['message' => '提交成功。', 'success' => 'true', 'data' => 0]);
        }
        return response()->json(['message' => '提交成功。', 'success' => 'true', 'data' => 1]);
    }

    /**
     * 获取短信验证码
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSmsCode()
    {
        $mobile = \request()->post('mobile', '');
        if (!isMobile($mobile)) {
            return response()->json(['message' => '手机号错误', 'success' => 'false']);
        }
        $code = SmsService::getCode($mobile);
        if (!$code[0]) {
            return response()->json(['message' => $code[1], 'success' => 'false']);
        }
        $res = SmsService::sendSms($mobile, $code[1]);
        if (!$res[0]) {
            return response()->json(['message' => $res[1], 'success' => 'false']);
        }
        if ($res[1]['Code'] != 'OK') {
            return response()->json(['message' => $res[1]['Message'], 'success' => 'false']);
        }
        return response()->json(['message' => $code, 'success' => 'true']);
    }

    /**
     * 绑定手机
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindMobile()
    {
        $mobile = \request()->post('mobile', '');
        $code = \request()->post('sms_code', '');
        if (!isMobile($mobile)) {
            return response()->json(['message' => '手机号错误', 'success' => 'false']);
        }
        if (empty($code)) {
            return response()->json(['message' => '请输入验证码', 'success' => 'false']);
        }
        $check = SmsService::checkCode($mobile, $code);
        if (!$check[0]) {
            return response()->json(['message' => $check[1], 'success' => 'false']);
        }
        $user = \request()->userInfo;
        if ($user->mobile) {
            return response()->json(['message' => '您已绑定手机', 'success' => 'false']);
        }
        $hasMobile = DB::table('users')->where('mobile', $mobile)->count();
        if ($hasMobile) {
            return response()->json(['message' => '该手机号码已被绑定', 'success' => 'false']);
        }
        DB::table('users')->where('id', $user->id)->update(['mobile' => $mobile]);
        /*$gift = DB::table('user_balance_log')->where('union_id', $user->wx_unionid)
            ->where('from_type', MemberService::FromTypeBindMobile)
            ->count();
        if (!$gift) {
            // 增加用户乐游币
            MemberService::setMemberBalance(
                $user,
                MemberService::BalanceTypeLy,
                MemberService::FromTypeBindMobile,
                0,
                0,
                '手机号绑定奖励'
            );
            // 给上级增加
            if ($user->from_id) {
                $p = DB::table('users')->find($user->from_id);
                MemberService::setMemberBalance(
                    $p,
                    MemberService::BalanceTypeLy,
                    MemberService::FromTypeSubBindMobile,
                    $user->id,
                    0,
                    '好友手机号绑定奖励'
                );
            }
        }*/
        return response()->json(['message' => '绑定成功。', 'success' => 'true']);
    }


    /**
     * 绑定手机页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function bindMobilePage()
    {
        return view('user.bind_mobile');
    }

    /**
     * 登录页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loginPage()
    {
        return view('user.login');
    }

    /**
     * 登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $mobile = \request()->post('mobile', '');
        $code = \request()->post('sms_code', '');
        if (!isMobile($mobile)) {
            return response()->json(['message' => '手机号错误', 'success' => 'false']);
        }
        if (empty($code)) {
            return response()->json(['message' => '请输入验证码', 'success' => 'false']);
        }
        $check = SmsService::checkCode($mobile, $code);
        if (!$check[0]) {
            return response()->json(['message' => $check[1], 'success' => 'false']);
        }
        // 查询用户
        $userInfo = DB::table('users')->where('mobile', $mobile)->first();
        if (!$userInfo) {
            return response()->json(['message' => '新用户只能扫码登录', 'success' => 'false']);
        }
        //cookie('token', $token);
        Cookie::queue('token', $userInfo->token);
        Cookie::queue('user_id', $userInfo->id, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = false);
        MemberService::refreshLevel($userInfo);
        return response()->json(['message' => '登录成功', 'success' => 'true', 'data' => [
            'id' => $userInfo->id,
            'username' => $userInfo->username
        ]], 200);
    }

    public function getPhoneInfo(){
        $mobile = \request()->post('mobile', '');
        $hasMobile = DB::table('users')->where('mobile', $mobile)->count();
        if ($hasMobile) {
            return response()->json(['message' => '您已经是老用户了', 'success' => 'false','info'=>$hasMobile]);
        }
        return response()->json(['message' => '成功', 'success' => 'true','info'=>$hasMobile]);
    }


    public function dhScript(){
//        /如果设定了yes回调，需进行手工关闭
        // $id = 1893147; //从哪条数据开始执行
        $id = 1893453;
        // $id = 1897498;
        // $row = DB::table('draw_log')->where('id', '=', $id)->limit(50)->get();
        $row = DB::table('draw_log')->where('id', '>', $id)->where('sync_api', 1)->where('status', 2)->where('game_url', "!=","")->limit(50)->get();
        // var_dump($row);
        foreach ($row as $key=>$value){
            $value = (array)$value;
            if(!empty($value["game_id"])){
                $ret =  $this->DhCurl($value["id"],$value["draw_id"]);
                if ($ret == true) {
                    DB::table('draw_log')
                        ->where('id', $value["id"])
                        ->update([
                            'status' => 1,
                            'sync_api' => 2,
                            'handle_time'=>date("Y-m-d H:i:s")

                        ]);
                    $this->sendWxTemplateMsg($value["id"]);
                }else{
                    DB::table('draw_log')
                        ->where('id', $value["id"])
                        ->update([
//                            'status' => 3,
                            'sync_api' => 2,
                            'handle_time'=>date("Y-m-d H:i:s")
                        ]);
                }
            }else{
                DB::table('draw_log')
                    ->where('id', $value["id"])
                    ->update([
//                            'status' => 3,
                        'sync_api' => 2,
                        'handle_time'=>date("Y-m-d H:i:s")
                    ]);
            }

        }

    }


    public  function DhCurl($id,$draw_id)
    {
        try {
            $ratio = 1;
            $jili = 1;
            $fujia= 1;
            $jifen = 1;
            $zhuangbei = 1;
            $info = (array)DB::table('draw_log')->where('id', $id)->first();
            $balance_type = $info["balance_type"];
            $money =  $info['money'];
            $gameuser  =  $info['game_num'];
            $gameId =  $info['game_id'];
            $gameInfo =  (array)DB::table('game_data')->where('id', $gameId)->first();
            $tqbh = explode(',',$gameInfo["area_code"]);//通区编号   下标0是通区人民币,1是通区元宝,2是人民币补发
            if (count($tqbh) <3) { //没设置3个直接重置
                return false;
            }
            // var_dump($tqbh);DIE;
            $platform_id = $gameInfo["dh_plat_id"]; //平臺id
            $platformInfo = (array)DB::table('dh_platform')->where("id","=",$platform_id)->first(); //平台详情
            $apiKey =   $platformInfo['app_key'];
            $iuserId = $platformInfo['iuserid'];
            $timeOut = 10;

            if ($money <= 20 ){//人民币补发
                $codeType = $tqbh[2];
            }else{//通区元宝
                $codeType = $tqbh[1];
            }
            if ($draw_id == 0) { //余额兑换
                $money = $money / 100;
                if($balance_type == 2){
                    $codeType = $tqbh[2];
                }else{
                    $codeType = $tqbh[0];
                }

            }
            if ($balance_type == 6){//新红包币
                $money = $money * 100;
            }
            $param = ['gameid'=>$codeType,"money"=>$money,"gameuser"=>$gameuser,"ratio"=>$ratio,"jili"=>$jili,"fujia"=>$fujia,"jifen"=>$jifen,"zhuangbei"=>$zhuangbei];
            $sign = md5('1.0'.$iuserId.'manualpay'.$apiKey);
            $curlData = ['iversrion'=>'1.0','iuserid'=>$iuserId,'itype'=>'manualpay','idata'=>json_encode($param),'isign'=>$sign];
            $httph = curl_init();
            curl_setopt($httph, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
            curl_setopt($httph, CURLOPT_URL, 'http://api.64pay.com/api.html');
            curl_setopt($httph, CURLOPT_POST, 1); //设置为POST方式
            //curl_setopt($httph, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            curl_setopt($httph, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($httph, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($httph, CURLOPT_POSTFIELDS, json_encode($curlData));
            curl_setopt($httph, CURLOPT_AUTOREFERER, 1);
            curl_setopt($httph, CURLOPT_TIMEOUT, $timeOut);
            //curl_setopt($httph, CURLOPT_HEADER, 0);
            $rst = curl_exec($httph);
            curl_close($httph);
            $result =  json_decode($rst, true);
            if ($result['resultcode'] == 200){
                return true;
            }else{
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    public function sendWxTemplateMsg($id, $status = 1, $msg = '')
    {
        $row = DB::table('draw_log')
            ->where('id', $id)
            ->first();
        $user = DB::table('users')
            ->where('id', $row->user_id)
            ->first();
//        $config = config('wechat');

//        if ($msg == "") {
//            $msg = "充值成功";
//        } else {
//            $msg = '失败原因：' . $msg;
//        }
//
        if ($row->money < 10 ){
            $money = $row->money * 100;
        }else{
            $money = $row->money;
        }
        sendRechargeWxTemplateMsg(
            $user->wx_unionid, $row->game_num, $row->game_url, $money, $user->money
        );
//        $app = Factory::officialAccount($config);?
//        $ret = $app->template_message->send([
//            'touser' => $user->wx_unionid,
//            'template_id' => 'JH7dKP1aBkf09VWtcW_pX_lusRKJ4Q9NiPRMTq3K0MQ',
//            'url' => 'https://l3y.com/',
//            'data' => [
//                'first' => '乐享游福利赠送通知',
//                'keyword1' => $row->game_num,
//                'keyword2' => $row->game_url,
//                'keyword3' => $row->date . ' ' . $row->game_server . ' '. $row->money,
//                'keyword4' => $status == 1 ? '成功':'失败',
//                'keyword5' => $msg,
//                'remark' => '祝您游戏愉快,如果有其他问题可咨询微信专属客服'
//            ],
//        ]);
        // Log::info($ret);
    }
    //游戏余额补发
    public function gameMoneyReissue()
    {
        GameMoneyReissue::gameMoneyReissue("202310101455441495983851");
//        try {
//            $ratio = 1;
//            $jili = 1;
//            $fujia= 1;
//            $jifen = 1;
//            $zhuangbei = 1;
//            $row = DB::table('game_recharge_order')->where('pay_status', '=', 1)->where('pay_status', '=', 1)->where('order_type', '=', 1)->where('is_reissue', "=",0)->limit(5)->get();
//            foreach ($row as $key=>$value) {
//                $info = (array)$value;
//                $money =  $info['money'];//金额
//                $gameuser  =  $info['game_account']; //游戏账号
//                $platform_id = $info["pay_plat_id"]; //平臺id
//                $platformInfo = (array)DB::table('pay_platform')->where("id","=",$platform_id)->first(); //平台详情
//                $apiKey =   $platformInfo['app_key'];
//                $iuserId = $platformInfo['user_id'];
//                $timeOut = 10;
//                $codeType = $platformInfo['game_id'];
//                $param = ['gameid'=>$codeType,"money"=>$money,"gameuser"=>$gameuser,"ratio"=>$ratio,"jili"=>$jili,"fujia"=>$fujia,"jifen"=>$jifen,"zhuangbei"=>$zhuangbei];
//                $sign = md5('1.0'.$iuserId.'manualpay'.$apiKey);
//                $curlData = ['iversrion'=>'1.0','iuserid'=>$iuserId,'itype'=>'manualpay','idata'=>json_encode($param),'isign'=>$sign];
//                $httph = curl_init();
//                curl_setopt($httph, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
//                curl_setopt($httph, CURLOPT_URL, 'http://api.64pay.com/api.html');
//                curl_setopt($httph, CURLOPT_POST, 1); //设置为POST方式
//                //curl_setopt($httph, CURLOPT_CUSTOMREQUEST, "POST");
//                curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, false);
//                curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, false);
//                curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
//                curl_setopt($httph, CURLOPT_RETURNTRANSFER, true);
//                curl_setopt($httph, CURLOPT_FOLLOWLOCATION, 1);
//                curl_setopt($httph, CURLOPT_POSTFIELDS, json_encode($curlData));
//                curl_setopt($httph, CURLOPT_AUTOREFERER, 1);
//                curl_setopt($httph, CURLOPT_TIMEOUT, $timeOut);
//                //curl_setopt($httph, CURLOPT_HEADER, 0);
//                $rst = curl_exec($httph);
//                curl_close($httph);
//                $result =  json_decode($rst, true);
//                if ($result['resultcode'] == 200){
//                    DB::table('game_recharge_order')
//                        ->where('id', $info["id"])
//                        ->update([
//                            'is_reissue' => 1,
//                        ]);
//                }else{
//                    $order = [
//                        'pay_plat_id' => $info["pay_plat_id"],
//                        'user_id' => $info["user_id"],
//                        'unionid' => $info["unionid"],
//                        'money' => $info["money"],
//                        'req_params' => $info["req_params"],
//                        'pay_type' => $info["pay_type"],
//                        'order_no' => $info["order_no"],
//                        'plat_order_no' => $info["plat_order_no"],
//                        'contact' => $info["contact"] ?? '',
//                        'pay_status' => 2,
//                        'game_account' => $info["game_account"] ?? '',
//                        'game_version' => $info["game_version"]  ?? '',
//                        'game_server' => $info["game_server"] ?? '',
//                        'game_role' => $info["game_role"] ?? '',
//                        'create_time' => time(),
//                        'update_time' => time(),
//                        'site_host' => $_SERVER['HTTP_HOST'] ?? '',
//                        'order_type' => 1,
//                    ];
//                    DB::table('game_recharge_order_error')->insertGetId($order);
//                }
//            }
//            echo "批量充值成功";
//        } catch (\Exception $e) {
//            return false;
//        }
    }

    public function dhScriptcs(){
        $ratio = 1;
        $jili = 1;
        $fujia= 1;
        $jifen = 1;
        $timeOut = 10;
        $zhuangbei = 1;
        $iuserId = 17038;
        $gameuser = "zhoufei";
        $apiKey = "e9ikRrxmIyMt62QvMDtWHkkHvS0LGwua";
        $param = ['gameid'=>11418626,"money"=>1000,"gameuser"=>$gameuser,"ratio"=>$ratio,"jili"=>$jili,"fujia"=>$fujia,"jifen"=>$jifen,"zhuangbei"=>$zhuangbei];
        $sign = md5('1.0'.$iuserId.'manualpay'.$apiKey);
        $curlData = ['iversrion'=>'1.0','iuserid'=>$iuserId,'itype'=>'manualpay','idata'=>json_encode($param),'isign'=>$sign];
        $httph = curl_init();
        curl_setopt($httph, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
        curl_setopt($httph, CURLOPT_URL, 'http://api.64pay.com/api.html');
        curl_setopt($httph, CURLOPT_POST, 1); //设置为POST方式
        //curl_setopt($httph, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        curl_setopt($httph, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($httph, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($httph, CURLOPT_POSTFIELDS, json_encode($curlData));
        curl_setopt($httph, CURLOPT_AUTOREFERER, 1);
        curl_setopt($httph, CURLOPT_TIMEOUT, $timeOut);
        //curl_setopt($httph, CURLOPT_HEADER, 0);
        $rst = curl_exec($httph);
        curl_close($httph);
        $result =  json_decode($rst, true);

    }


    public  function DhCurlcs($id,$draw_id)
    {
        try {
            $ratio = 1;
            $jili = 1;
            $fujia= 1;
            $jifen = 1;
            $timeOut = 10;
            $zhuangbei = 1;
            $iuserId = 5724;
            $gameuser = "";
            $apiKey = "8ptJWRTJgqNcfjA5igjNTasvP5Lstoqz";
            $param = ['gameid'=>11410342,"money"=>1000,"gameuser"=>$gameuser,"ratio"=>$ratio,"jili"=>$jili,"fujia"=>$fujia,"jifen"=>$jifen,"zhuangbei"=>$zhuangbei];
            $sign = md5('1.0'.$iuserId.'manualpay'.$apiKey);
            $curlData = ['iversrion'=>'1.0','iuserid'=>$iuserId,'itype'=>'manualpay','idata'=>json_encode($param),'isign'=>$sign];
            $httph = curl_init();
            curl_setopt($httph, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
            curl_setopt($httph, CURLOPT_URL, 'http://api.64pay.com/api.html');
            curl_setopt($httph, CURLOPT_POST, 1); //设置为POST方式
            //curl_setopt($httph, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            curl_setopt($httph, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($httph, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($httph, CURLOPT_POSTFIELDS, json_encode($curlData));
            curl_setopt($httph, CURLOPT_AUTOREFERER, 1);
            curl_setopt($httph, CURLOPT_TIMEOUT, $timeOut);
            //curl_setopt($httph, CURLOPT_HEADER, 0);
            $rst = curl_exec($httph);
            curl_close($httph);
            $result =  json_decode($rst, true);
            if ($result['resultcode'] == 200){
                return true;
            }else{
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }


}
